//
//  ViewController.swift
//  WKWeb
//
//  Created by 郑东喜 on 2016/12/6.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController,WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate {
    
    var webView: WKWebView!
    
    
    var url : String = ""
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        print("viewWillAppear1")
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        

        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        configuration.userContentController = userContentController
        
        // 设置偏好设置
        let preferences = WKPreferences()
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        
        configuration.processPool = WKProcessPool()
        webView = WKWebView.init(frame: view.bounds, configuration: configuration)
        
        webView.uiDelegate = self
        webView.navigationDelegate = self
        
        
        //设置弹簧效果
        webView.scrollView.bounces = true
        
        if urlArray.count > 1 {
            let urlStr = urlArray.lastObject
            
            webView.load(URLRequest.init(url: URL.init(string: urlStr as! String)!))
        } else {
            DispatchQueue.main.async {
                let url = URL.init(string: "http://yungou.ie1e.com/app/cart.aspx")
                
                self.webView.load(URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 2.0))
            }
        }

        view.addSubview(webView)
        
        //添加刷新控件
        let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(refreshWebView(sender:)), for: UIControlEvents.valueChanged)
        webView.scrollView.addSubview(refreshControl)
    }
    
    //刷新函数
    func refreshWebView(sender: UIRefreshControl) {
        print("refersh")
        
        self.loadViewIfNeeded()
        
        sender.endRefreshing()
        
        
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }

    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
//        let hostname = navigationAction.request.url?.host?.lowercased()
    
        url = (navigationAction.request.url?.absoluteString)!

        print(url)
        
        print(urlArray.count)
        
        if navigationAction.navigationType == WKNavigationType.linkActivated {
            
            //如果为本身或者本身携带#的url进行自身刷新。
            if url == "http://yungou.ie1e.com/app/cart.aspx" || url == "http://yungou.ie1e.com/app/cart.aspx#" {
            
//            if url == "http://3g.163.com/touch/" {
            
                self.webView.load(URLRequest.init(url: URL.init(string: url)!))
                
                urlArray.removeAllObjects()
                
            } else {
                print(urlArray)
                urlArray.add(url)
                aaa(str: urlArray.lastObject as! String)
            }
            
//            ///判断
//            1首页，返回，数组清空

//            } else {
//
//            }
            
//            3.当前页不动
//            不满足。创建新页面（添加数组，最后一个元素）
            
//            4.判断
//            5.新页面才记录。
            
            
            //vc基础类
            decisionHandler(.cancel)


        } else {
            decisionHandler(.allow)
        }
    }
    
    //url---
    func aaa(str : String) -> Void {

        let vvv = BVC()
        vvv.url = str
        self.navigationController?.pushViewController(vvv, animated: true)
        
        
    }
    
    //获取标题
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.navigationItem.title = self.webView.title
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        decisionHandler(.allow)
    }


}


